import { defineEventHandler, getRequestURL } from "h3";
import sequelize from "../database/config";

export default defineEventHandler(async (event) => {
  const url = getRequestURL(event);

  // 只对API请求生效
  if (url.pathname.startsWith("/api/")) {
    console.log(`[DB Middleware] 处理请求: ${url.pathname}`);

    // 开启事务（根据需要）
    const transaction = await sequelize.transaction();
    event.context.dbTransaction = transaction; // 存入上下文供后续使用

    // 处理完请求后提交或回滚事务
    event.res.on("finish", async () => {
      if (event.res.statusCode >= 200 && event.res.statusCode < 400) {
        await transaction.commit();
        console.log(`[DB Middleware] 事务已提交: ${url.pathname}`);
      } else {
        await transaction.rollback();
        console.log(`[DB Middleware] 事务已回滚: ${url.pathname}`);
      }
    });
  }
});
